package com.wxd.modules.sys.controller;

import com.wxd.Exception.RRException;
import com.wxd.annotation.SysLog;
import com.wxd.modules.sys.entity.SysMenuEntity;
import com.wxd.modules.sys.service.SysMenuService;
import com.wxd.utils.Constant;
import com.wxd.utils.R;
import org.apache.catalina.security.SecurityUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

import static com.wxd.modules.sys.shiro.ShiroUtils.getUserId;
import static com.wxd.modules.sys.shiro.ShiroUtils.setSessionAttribute;

/**
 * 菜单管理
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends AbstractController{

    @Autowired
    private SysMenuService sysMenuService;
    /**
     * 导航菜单
     */
    @RequestMapping("/nav")
    public R nav()
    {
        List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(getUserId());
        return R.ok().put("menuList",menuList);
    }
    /**
     * 导航菜单,根据用户的某个角色Id获取对应的导航菜单
     */
    @RequestMapping("/roleNav/{roleId}")
    public R roleNav(@PathVariable("roleId") Long roleId)
    {
        //将用户的当前显示角色roleId保存到session
        setSessionAttribute("roleId",roleId);
        List<SysMenuEntity> roleMenuList = sysMenuService.getUserRoleMenuList(getUserId(),roleId);
        return R.ok().put("roleMenuList",roleMenuList);
    }
    /**
     *所有菜单列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:menu:list")
    public List<SysMenuEntity> list()
    {
        List<SysMenuEntity> menuList = sysMenuService.list();
        for(SysMenuEntity sysMenuEntity:menuList)
        {
            SysMenuEntity parentMenuEntity = sysMenuService.getById(sysMenuEntity.getParentId());
            if(parentMenuEntity!=null)
            {
                sysMenuEntity.setParentName(parentMenuEntity.getName());
            }
        }
         //按照orderNum从小到大排序。依靠compare
        Collections.sort(menuList, new Comparator<SysMenuEntity>() {
            @Override
            public int compare(SysMenuEntity o1, SysMenuEntity o2) {
                return o1.getOrderNum()-o2.getOrderNum();
            }
        });
        return menuList;
    }

    /**
     * 选择菜单(添加、修改菜单)
     */
    @RequestMapping("/select")
    @RequiresPermissions("sys:menu:select")
    public R select(){
        //查询列表数据
        List<SysMenuEntity> menuList = sysMenuService.queryNotButtonList();

       //添加顶级菜单
       /* SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("一级菜单");
        root.setParentId(-1L);
        root.setOpen(true);
        menuList.add(root);*/

        return R.ok().put("menuList", menuList);
    }
    /**
     * 某菜单信息
     */
    @RequestMapping("/info/{menuId}")
    @RequiresPermissions("sys:menu:info")
    public R info(@PathVariable("menuId") Long menuId)
    {
        SysMenuEntity menu = sysMenuService.getById(menuId);
        return R.ok().put("menu",menu);
    }
    /**
     * 保存菜单
     */
    @SysLog("保存菜单")
    @RequestMapping("/save")
    @RequiresPermissions("sys:menu:save")
    public R save(@RequestBody SysMenuEntity menu){
        //数据校验
        verifyForm(menu);
        sysMenuService.save(menu);
        return R.ok();
    }

    /**
     *修改
     */
    @SysLog("修改菜单")
    @RequestMapping("/update")
    @RequiresPermissions("sys:menu:update")
     public R update(@RequestBody SysMenuEntity menu)
     {
         //数据校验
         verifyForm(menu);
         sysMenuService.updateById(menu);
         return R.ok();
     }
    /**
     * 删除
     */
    @SysLog("删除菜单")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:menu:delete")
    public R delete(long menuId)
    {
        if(menuId<35)
        {
            return R.error("系统菜单不能删除");
        }
        //判断是否有子菜单或者按钮
        List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
        if(menuList.size()>0)
        {
            return  R.error("请先删除子菜单或按钮");
        }
        sysMenuService.delete(menuId);
        return R.ok();
    }
    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysMenuEntity menu)
    {
        if(StringUtils.isBlank(menu.getName()))
        {
            throw new RRException("菜单名称不能为空");
        }
        if(menu.getParentId()==null){
            throw  new RRException("上级菜单不能为空");
        }
        //菜单
        if(menu.getType()== Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(menu.getUrl())) {
                throw new RRException("菜单URL不能为空");
            }
        }
        //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if(menu.getParentId()!=0)
        {
            SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
            parentType=parentMenu.getType();
        }
        //目录，菜单
        if(menu.getType()==Constant.MenuType.CATALOG.getValue()||
                menu.getType()==Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                throw new RRException("上级菜单只能为目录类型");
            }
        }
        //按钮
        if(menu.getType()==Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                throw new RRException("上级菜单只能为菜单类型");
            }
        }

    }
}
